package com.iwinding.ladygg.ui.act;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;


import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.util.NetUtils;
import com.iwinding.ladygg.ICaneApplication;
import com.iwinding.ladygg.R;
import com.iwinding.ladygg.SOSUserProfileProvider;
import com.iwinding.ladygg.bluetooth.TMApi;
import com.iwinding.ladygg.bluetooth.impblekit.BleKitManager;
import com.iwinding.ladygg.bluetooth.impblekit.ICaneBleApi;
import com.iwinding.ladygg.constant.SPConstant;
import com.iwinding.ladygg.event.BaseEvent;
import com.iwinding.ladygg.net.RequestManager;
import com.iwinding.ladygg.net.callback.BaseRpCallback;
import com.iwinding.ladygg.net.response.BaseRopnse;
import com.iwinding.ladygg.net.response.LoginRp;
import com.iwinding.ladygg.net.response.ThirdPartyLoginRp;
import com.iwinding.ladygg.ui.auth.QQAuthApi;
import com.iwinding.ladygg.ui.auth.WeiboAuthApi;
import com.iwinding.ladygg.ui.fragment.ContactsFragment;
import com.iwinding.ladygg.ui.fragment.MyselfFragment;
import com.iwinding.ladygg.ui.fragment.NoticeFragment;
import com.iwinding.ladygg.utils.LogUtil;
import com.iwinding.ladygg.utils.SPUtils;
import com.iwinding.ladygg.utils.SystemUtil;
import com.iwinding.ladygg.utils.ToastUtil;
import com.iwinding.ladygg.widget.bottomBar.BottomBar;
import com.yayandroid.theactivitymanager.TheActivityManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;


/**
 * 首页
 * Created by Administrator on 2016/6/7.
 */
public class MainActivity extends FragmentBaseActivity {

    private BottomBar bottomBar;

    private NoticeFragment noticeFragment;
    private ContactsFragment contactsFragment;
    private MyselfFragment myselfFragment;

    private MyConnectionListener myConnectionListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            //此处可发送广播唤醒想要启动的acitivity
            finish();
            return;
        }
        ICaneApplication iCaneApplication = ((ICaneApplication) getApplicationContext());
        LoginRp loginRp = iCaneApplication.getmLoginRp();
        if (loginRp == null) {
            iCaneApplication.setmLoginRp(SystemUtil.getLoginRp(this));
        }

        EventBus.getDefault().register(this);
        //初始化联系人
        SOSUserProfileProvider.getInstance().initContext(mOAAplication);
        SOSUserProfileProvider.getInstance().initContactList();
        EaseUI.getInstance().setUserProfileProvider(SOSUserProfileProvider.getInstance());

        mBack.setVisibility(View.INVISIBLE);

        initView();

//        isNeedLogin();
        if (savedInstanceState != null) {
            FragmentManager manager = getSupportFragmentManager();//重新创建Manager，防止此对象为空
            manager.popBackStackImmediate(null, 1);//弹出所有fragment
        }

        initBluetooth();

        myConnectionListener = new MyConnectionListener();
        EMClient.getInstance().addConnectionListener(myConnectionListener);
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
// super.onSaveInstanceState(outState);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
//        int process = intent.getIntExtra(PROCESS, 1);
//        bottomBar.setSelectIndex(0);
//        setMenuListener();
//        bottomBar.setMenuItems(this, R.menu.bottombar_menu);
//
//        if (processFragment != null) {
//            processFragment.OpenD_AFA(process);
//        }
    }

    @Override
    protected int getLayoutID() {
        return R.layout.icane_activity_main;
    }

    @Override
    protected int getFragmentID() {
        return R.id.main_frame;
    }

    @Override
    protected void handleFragments(FragmentTransaction transaction, Fragment currentFragment, List<Fragment> list) {
        if (list != null) {
            for (Fragment frag : list) {
                if (frag != null) {
                    if (frag != currentFragment) {
                        transaction.hide(frag);
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().removeConnectionListener(myConnectionListener);
//        BluetoothManager.getInstance().unBindService();
        clearFragments();
        EventBus.getDefault().unregister(this);
        TMApi.getInstance().onDistory();
//        AMMapHelper.getInstance().stopLocation();
    }

    private void initView() {
        bottomBar = (BottomBar) findViewById(R.id.tab_bottom);
        //选择第一页流程图
        bottomBar.setSelectIndex(0);
        setMenuListener();
        bottomBar.setMenuItems(this, R.menu.bottombar_menu);
    }

    private void setMenuListener() {
        bottomBar.setOnMenuTabClickListener(new BottomBar.OnMenuTabClickListener() {
            @Override
            public void onMenuTabClick(View view, int postion, CharSequence title) {
                updateTitle(postion, title.toString());
                switch (postion) {
                    case 0:
                        if (noticeFragment == null) {
                            noticeFragment = new NoticeFragment();
                            Bundle bundle = new Bundle();
                            bundle.putString("index", "notice");
                            noticeFragment.setArguments(bundle);
                        }
                        updateFragment(noticeFragment);
                        break;
                    case 1:
                        if (contactsFragment == null) {
                            contactsFragment = new ContactsFragment();
                            Bundle bundle = new Bundle();
                            bundle.putString("index", "contacts");
                            contactsFragment.setArguments(bundle);
                        }
                        updateFragment(contactsFragment);
                        break;
                    case 2:
                        if (myselfFragment == null) {
                            myselfFragment = new MyselfFragment();
                            Bundle bundle = new Bundle();
                            bundle.putString("index", "myself");
                            myselfFragment.setArguments(bundle);
                        }
                        updateFragment(myselfFragment);
                        break;
                }
            }
        });
    }

    public void updateTitle(int postion, String title) {
        setTitleStr(title);
        switch (postion) {
            case 0:
                mRight.setVisibility(View.GONE);
//                mRightTxt.setVisibility(View.GONE);
                setmRightTxtStr(getString(R.string.icane_test), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(MainActivity.this, SosTestActivity.class));
                    }
                });
                break;
            case 1:
                mRightTxt.setVisibility(View.GONE);
                setmRightIcon(R.mipmap.pub_add_friend, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(MainActivity.this, AddFriendActivity.class));
                    }
                });
                break;
            case 2:
                mRightTxt.setVisibility(View.GONE);
                mRight.setVisibility(View.INVISIBLE);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        switch (bottomBar.getSelectIndex()) {
            case 0:
                mRight.setVisibility(View.GONE);
                mRightTxt.setVisibility(View.VISIBLE);
//                setmRightTxtStr(getString(R.string.icane_test), new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        startActivity(new Intent(MainActivity.this, SosTestActivity.class));
//                    }
//                });
                break;
            case 1:
                mRightTxt.setVisibility(View.GONE);
                setmRightIcon(R.mipmap.pub_add_friend, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(MainActivity.this, AddFriendActivity.class));
                    }
                });
                break;
            case 2:
                mRightTxt.setVisibility(View.GONE);
                mRight.setVisibility(View.INVISIBLE);
                break;
        }
    }

    private void initBluetooth() {
//        BluetoothManager.getInstance().initContext(this);
//        BluetoothManager.getInstance().initBleService();
//        ICaneBleRoutine.getInstance().initContext(this);
//        BluetoothManager.getInstance().setOnDataAvailableListener(ICaneBleRoutine.getInstance());
////        如果已经连接蓝牙，则设置看是否能连接上iCane;
//        ICaneBleRoutine.getInstance().setICaneConnBluetoothGatt();

//        BleManager.getInstance().initBle(this);
//        ICaneBleApi.getInstance().initContext(this);
//        ICaneBleApi.getInstance().setNeedAutoConnect(false);
//        BleManager.getInstance().setAutoConnBle(ICaneBleApi.getInstance());
        BleKitManager.getInstance().initBle(this);
        ICaneBleApi.getInstance().initContext(this);
        ICaneBleApi.getInstance().initAutoDevice();
        ICaneBleApi.getInstance().setNeedAutoConnect(true);
        BleKitManager.getInstance().setAutoConnBle(ICaneBleApi.getInstance());


    }

    @Subscribe
    public void onEvent(BaseEvent event) {
    }

//    void openProcessTab(int tab) {
//        int process = tab;
//
//        if (noticeFragment != null) {
//            bottomBar.setSelectIndex(0);
//            setMenuListener();
//            bottomBar.setMenuItems(this, R.menu.bottombar_menu);
//
//        }
//    }


    private long exitTime = 0;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            ToastUtil.exitApp(this);
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

//    public void getContacts(){
//        RequestManager.postContacts(this, new ContactsCallback() {
//            @Override
//            public void onResult(List<UserRp> userRps) {
//                List<Users> userses = new ArrayList<Users>();
//                for (UserRp userRp:userRps){
//                    userses.add(userRp.toUsers());
//                }
//                UserDBHelper.getInstance(MainActivity.this).addAllUsers(userses);
//            }
//
//            @Override
//            public void onFail(String errorMsg) {
//
//            }
//        });
//    }

    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        LogUtil.i("@hzy", "----------USER_REMOVED");
                        // 显示帐号已经被移除
                        logout(MainActivity.this);
                    } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        LogUtil.i("@hzy", "----------USER_LOGIN_ANOTHER_DEVICE");
                        // 显示帐号在其他设备登录
                        logout(MainActivity.this);
                    } else {
                        if (NetUtils.hasNetwork(MainActivity.this)) {
                            //连接不到聊天服务器
                        } else {
                            //当前网络不可用，请检查网络设置
                        }
                    }
                }
            });
        }
    }

    void logout(final Context mContext) {
        RequestManager.postLogout(mContext, new BaseRpCallback<BaseRopnse>() {

            @Override
            public BaseRopnse parseResponse(BaseRopnse response, int id) {
                return response;
            }

            @Override
            public void onResult(BaseRopnse baseRopnse) {
                if (mOAAplication.getmLoginRp() != null) {
                    if (mOAAplication.getmLoginRp() instanceof ThirdPartyLoginRp) {
                        ThirdPartyLoginRp thirdPartyLoginRp = SystemUtil.getThreeLoginRp(mContext);
                        if (!TextUtils.isEmpty(thirdPartyLoginRp.qqToken)) {
                            QQAuthApi.getInstance().logout();
                        }
                        if (!TextUtils.isEmpty(thirdPartyLoginRp.weiboToken)) {
                            WeiboAuthApi.getInstance().logout();
                        }
                    }
                }
                mOAAplication.setmLoginRp(null);
                SPUtils.putSpProperty(mContext, SPConstant.IS_EXIT, true);
                SPUtils.putSpProperty(mContext, SPConstant.COOKIE, "");
                LogUtil.i("@hzy", "----------logout");
                ToastUtil.openBaseToast(mContext, R.string.login_out_other, Toast.LENGTH_SHORT);
                Intent intent = new Intent(mContext, LoginActivity.class);
                mContext.startActivity(intent);
                TheActivityManager.getInstance().finishInstance(MainActivity.class);
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }
        });
    }


}
